<template>
  <div class="main">
    <a-layout class="layout">
      <a-layout-header class="header">
        <div>
          <span></span>
          入职通知内容
        </div>
        <a-button @click="handleClick" type="primary">
          <template #icon>
            <icon-edit />
          </template>
          <template #default>编辑</template></a-button
        >
      </a-layout-header>
      <a-layout-content class="main">
        <div class="content">
          <section class="control">
            <a-input-search
              v-model="searchVal"
              search-button
              @input="onSearch"
              @press-enter="onSearch"
              placeholder="快速搜索变量"
              class="input"
            ></a-input-search>
            <a-tabs :default-active-key="0">
              <a-tab-pane
                :key="index"
                :title="item.subDetail.cnName"
                v-for="(item, index) in currControlData"
              >
                <a-space wrap>
                  <a-button
                    v-for="(item2, index2) in item.subDetail.subRelDetail"
                    :key="item2.id"
                    @click="
                      inputLabel(
                        item2,
                        (() => {
                          let num = index2;
                          for (let i = 0; i < index2; i++) {
                            num +=
                              currControlData[i].subDetail.subRelDetail.length;
                          }
                          return num;
                        })()
                      )
                    "
                    >{{ item2.ctlCnName }}
                  </a-button>
                </a-space>
              </a-tab-pane>
            </a-tabs>
          </section>
          <section>
            <RichTextNew
              v-model:content="content"
              :width="1000"
              ref="rich"
            ></RichTextNew>
          </section>
        </div>
        <!-- <a-scrollbar style="height: 100%; overflow: auto">
          <div style="width: 100vw - 80px">
            <a-space wrap>
              <a-button
                v-for="(item, index) in list"
                :key="index"
                @click="inputLabel(item, index)"
                >#{{ item.ctlCnName }}#</a-button
              >
            </a-space>
          </div>
        </a-scrollbar>

        <RichTextNew v-model:content="content" ref="rich"></RichTextNew> -->
      </a-layout-content>
    </a-layout>
    <a-layout class="layout">
      <a-layout-header class="header">
        <div>
          <span></span>
          入职材料1
        </div>
        <a-button @click="fileOk" type="primary">新增</a-button>
      </a-layout-header>
      <a-layout-content class="main">
        <a-table :data="table" stripe>
          <template #columns>
            <a-table-column align="center" :width="80">
              <template #title> 序号 </template>
              <template #cell="{ rowIndex }">
                {{ rowIndex + 1 }}
              </template>
            </a-table-column>
            <a-table-column
              :width="200"
              dataIndex="stuffName"
              align="center"
              title="材料名称"
            >
              <template #cell="{ record }">
                <a-input v-model="record.stuffName"></a-input>
              </template>
            </a-table-column>
            <a-table-column
              :width="200"
              dataIndex="stuffContent"
              align="center"
              title="提交要求"
            >
              <template #cell="{ record }">
                <a-input v-model="record.stuffContent"></a-input>
              </template>
            </a-table-column>
            <a-table-column
              title="操作"
              align="center"
              :width="120"
              fixed="right"
            >
              <template #cell="{ record, rowIndex }">
                <!-- <a-tooltip content="编辑">
                  <icon-font
                    @click="edit(record)"
                    type="icon-edit"
                    :size="26"
                    :style="{
                      marginRight: '10px',
                      cursor: 'pointer'
                    }"
                  />
                </a-tooltip> -->
                <a-tooltip content="删除" position="left">
                  <a-popconfirm
                    content="是否确认删除该条数据?"
                    @ok="del(record.id, rowIndex)"
                  >
                    <icon-font
                      type="icon-delete"
                      :size="26"
                      :style="{
                        cursor: 'pointer',
                        marginRight: '10px'
                      }"
                    />
                  </a-popconfirm>
                </a-tooltip>
              </template>
            </a-table-column>
          </template>
        </a-table>
      </a-layout-content>
    </a-layout>
    <!-- <a-drawer
      :width="500"
      :visible="visible"
      @ok="handleOk"
      @cancel="handleCancel"
      unmountOnClose
    >
      <template #title> 基础信息 </template>
      <div v-for="(item, index) in labelList" :key="item.ctlCode">
        <p>{{ item.subDetail.cnName }}</p>
        <a-table
          stripe
          :data="item.subDetail.subRelDetail"
          @change="
            (data, extra, currData, index1) =>
              handleChange(data, extra, currData, index)
          "
          :draggable="{ type: 'handle', width: 40 }"
          :pagination="false"
        >
          <template #columns>
            <a-table-column align="center" :width="200">
              <template #title> 字段名称 </template>
              <template #cell="{ record }">
                {{ record.ctlCnName }}
              </template>
            </a-table-column>
            <a-table-column align="center" :width="80">
              <template #title> 是否显示 </template>
              <template #cell="{ record }">
                <a-checkbox v-model="record.isShow"></a-checkbox>
              </template>
            </a-table-column>
          </template>
        </a-table>
      </div>
    </a-drawer> -->
    <!-- <a-modal v-model:visible="modalShow" @ok="fileOk" @cancel="fileCancel">
      <template #title> 新增材料 </template>
      <a-form :model="form">
        <a-form-item
          field="stuffName"
          label="材料名称："
          :rules="stuffNameRules"
        >
          <a-input v-model="form.stuffName" placeholder="请输入" />
        </a-form-item>
        <a-form-item field="stuffContent" label="提交要求：">
          <a-textarea
            v-model="form.stuffContent"
            placeholder="请输入"
            allow-clear
          />
        </a-form-item>
      </a-form>
    </a-modal> -->
  </div>
</template>
<script setup lang="ts">
import {
  DelOnboardingInformTemplateDetail,
  AddOnboardingInformTemplateDetail
} from '@/apis/management/personnel/baseSetting/TransactionSetting';
import { GetBusinessModalData } from '@/apis/controltotal';
import { cloneDeep } from 'lodash';

import {
  GetEntryScheme,
  GetEntrySchemeById
} from '@/apis/management/personnel/baseSetting/TransactionSetting';
import { materials, file, stuff } from '../type';
import clonedeep from 'lodash.clonedeep';
import { changeControlData } from '@/utils/control';
const props = withDefaults(
  // 参数说明
  defineProps<{
    materialData?: materials[];
    id?: number;
  }>(),
  {
    materialData: () => {
      return [];
    }
  }
);
let originControlData = ref([]), // 储存原始控件信息
  currControlData = ref<any>([]), // 储存当前控件信息
  searchVal = ref('');

// tab选项初始数据
const controlList: any = ref();
// 初始化数据
const init = async () => {
  // const {
  //   funcCtlInfos: { children }
  // } = (await GetBusinessModalData({
  //   funcCode: 'SER_FUNC65E1F1B346CF47BC952C91D24207EDC4'
  // })) as any;
  // 获取控件总集数据
  const { funcCtlInfos }: any = await GetBusinessModalData({
    funcCode: 'SER_FUNC65E1F1B346CF47BC952C91D24207EDC4'
  });
  labelList.value = funcCtlInfos.children;

  // const res: any = await GetEntryScheme({ required: 1 });
  // const data: any = await GetEntrySchemeById({
  //   id: res.content[0].id
  // });
  // labelList.value = data?.splice(0, 2);
  controlList.value = changeControlData(funcCtlInfos, 'ctlDetail');
  originControlData.value = funcCtlInfos.children;
  currControlData.value = cloneDeep(funcCtlInfos.children);
  labelList.value.forEach((ele1: any) => {
    ele1.subDetail.subRelDetail.forEach((ele2: any) => {
      ele2.isShow = true;
    });
  });
  console.log('====================================children ');
  console.log(labelList.value);
  console.log('====================================');
};
init();

// 搜索框
const onSearch = () => {
  currControlData.value = [];
  if (searchVal.value === '') {
    currControlData.value = cloneDeep(originControlData.value);
  } else {
    for (let item of originControlData.value) {
      item.subDetail.subRelDetail.forEach((item2: any) => {
        if (item2.ctlCnName.includes(searchVal.value)) {
          // 判断如果该控件所属的子集不存在，则创建一个子集，否则直接将控件信息赋值给subRelDetail
          if (
            currControlData.value[currControlData.value.length - 1]?.id !==
            item.id
          ) {
            currControlData.value.push({
              id: item.id,
              subDetail: {
                cnName: item.subDetail.cnName,
                subRelDetail: []
              }
            });
          }
          currControlData.value[
            currControlData.value.length - 1
          ].subDetail.subRelDetail.push(item2);
        }
      });
    }
  }
};

const table = ref();
const visible = ref(false);
const modalShow = ref(false);
// 打开编辑tab选项
const handleClick = () => {
  visible.value = true;
};
// 关闭新增材料
const fileCancel = () => {
  for (let key in form) {
    form[key] = null;
  }
  modalShow.value = false;
};
// 新增材料
const fileOk = async () => {
  const newArr = clonedeep(props.materialData) || [];
  // if (form.id) {
  //   let editNewArr = newArr.filter((ele: any) => ele.id === form.id);
  //   console.log('fileOk =', form.id, editNewArr, newArr);
  //   editNewArr[0].stuffName = form.stuffName;
  //   editNewArr[0].stuffContent = form.stuffContent;
  // } else if (props.id) {
  //   console.log('11111', form);
  //   form.hid = props.id;
  //   const res: any = await AddOnboardingInformTemplateDetail(form);
  //   form.id = res.id;
  //   newArr.push(clonedeep(form));
  // } else {
  console.log('newArr', clonedeep(newArr));
  newArr.push({
    codeArray: '',
    content: '',
    fileContent: '',
    fileName: '',
    oldcodeArray: [],
    stuffContent: '',
    stuffName: ''
  });
  // }

  emit('update:materialData', newArr);
  for (let key in form) {
    form[key] = null;
  }
  modalShow.value = false;
};
// 关闭编辑tab选项
const handleCancel = () => {
  visible.value = false;
};
// 关闭编辑tab选项
const handleOk = () => {
  visible.value = false;
};
const form = reactive<materials>({});
const stuffNameRules = {
  required: true,
  message: '请输入材料名称'
};
// 移动tab选项位置
const handleChange = (_data: any, _1, _2, i) => {
  labelList.value[i].subDetail.subRelDetail = _data;
};
// tab选项显示数据
const list = computed(() => {
  const arr: any = [];
  labelList.value?.forEach((ele: any) => {
    arr.push(...ele.subDetail.subRelDetail);
  });
  return arr?.filter((ele: any) => ele.isShow);
});
// tab选项初始数据
const labelList: any = ref();
// 存放已用的tab数据
const verifyArr: any = reactive([]);
// 富文本ref
const rich = ref();
// 新增tab
const inputLabel = (item: any, ind: number) => {
  const arr = props.materialData[0]?.oldcodeArray;
  if (arr?.length !== 0) {
    if (
      !arr?.some((ele: any) => ele.ctlCode === controlList.value[ind].ctlCode)
    ) {
      arr?.push(controlList.value[ind]);
    }
  } else {
    arr?.push(controlList.value[ind]);
  }
  console.log(arr);

  const tag = `&nbsp;<span style="text-decoration: underline; color: #3598db; font-size: 12pt;">#${item.ctlCnName}#</span>&nbsp;`;
  nextTick(() => {
    rich.value.insertContent(tag);
  });
};
// 存放 富文本数据
const content = ref<string>();
// 删除材料
const del = async (id: number, ind: number) => {
  const newArr = clonedeep(props.materialData);

  if (id) {
    let index = 0;
    newArr.some((ele: any, ind: number) => {
      if (ele.id === id) index = ind;
    });
    newArr.splice(index, 1);
    await DelOnboardingInformTemplateDetail({ ids: [id] });
  } else {
    newArr.splice(ind, 1);
  }

  emit('update:materialData', newArr);
};
// 编辑材料
const edit = (data: any) => {
  form.id = data.id;
  form.stuffName = data.stuffName;
  form.stuffContent = data.stuffContent;
  modalShow.value = true;
};
watch(
  () => props.materialData,
  () => {
    console.log('props.materialData', props.materialData);
    table.value = props.materialData.slice(1);
    content.value = props.materialData[0]?.content || '';
    emit('update:content', props.materialData[0]?.content || '');
  }
);
watch(
  () => content.value,
  () => {
    const newArr = clonedeep(props.materialData);
    if (newArr[0]) {
      newArr[0].content = content.value;
    }
    emit('update:materialData', newArr);
  }
);
const emit = defineEmits(['update:content', 'update:materialData']);
</script>
<style lang="less" scoped>
.layout {
  .content {
    width: 100%;
    // display: grid;
    // grid-template-columns: 3fr 1fr;
    .control {
      .input {
        margin-bottom: 20px;
        width: 350px;
      }
    }
  }
  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 50px;
    line-height: 50px;
    padding: 0 20px;
    background-color: #f3f8fe;
    border-radius: 4px;
    margin-bottom: 20px;
    div {
      display: flex;
      align-items: center;
      span {
        margin: 0 20px;
        display: inline-block;
        width: 5px;
        height: 30px;
        background-color: #165dff;
      }
    }
  }
  .main {
    padding: 0 40px 20px 40px;
  }
  .arco-upload-wrapper {
    flex: 0;
  }
}
</style>
